# -*- coding: utf-8 -*-
# @author: liuhuaijin
# @email: liuhuaijin@shanshu.ai 
# @date: 2024/02/26

import os
import re
import logging
from logging.handlers import TimedRotatingFileHandler

LOG_PATH = os.path.join(os.path.dirname(__file__), 'logFiles')
if not os.path.exists(LOG_PATH):
    os.makedirs(LOG_PATH)

def format_logger(log_name, scheduled_save=True, stream=True):
    """
    日志初始化模块
    :param log_name: 日志及日志文件名称
    :param scheduled_save: 是否定时备份
    :param stream: 是否显示在屏幕
    :return:
    """
    log_file_name = log_name
    logger = logging.getLogger(log_name)
    # 如果已经有处理程序，则直接返回现有的logger
    if logger.hasHandlers():
        return logger
    logger.setLevel(logging.INFO)
    fmt = '[%(asctime)s %(levelname)7s] %(name)-12s %(message)s '
    log_formatter = logging.Formatter(fmt)
    if not os.path.exists(LOG_PATH):
        os.makedirs(LOG_PATH)
    if stream:
        handler_stream = logging.StreamHandler()
        handler_stream.setLevel(logging.INFO)
        handler_stream.setFormatter(log_formatter)
        logger.addHandler(handler_stream)
    if scheduled_save:
        handle_timerota = TimedRotatingFileHandler(
            '{0}/'.format(LOG_PATH) + log_file_name + '.log', when='W0', backupCount=10, encoding='utf8')
        handle_timerota.suffix = "%Y-%m-%d.log"
        handle_timerota.extMatch = re.compile('^\\d{4}-\\d{2}-\\d{2}(\\.\\w+)?$', re.ASCII)
        handle_timerota.setLevel(logging.INFO)
        handle_timerota.setFormatter(log_formatter)
        logger.addHandler(handle_timerota)
    else:
        handle_file = logging.FileHandler('{0}/'.format(LOG_PATH) + log_file_name)
        handle_file.setLevel(logging.INFO)
        handle_file.setFormatter(log_formatter)
        logging.getLogger().addHandler(handle_file)
    return logger


logger = format_logger('Flight', stream=True)

